<?php


namespace App\Http\Controllers;


use Google\Cloud\Speech\SpeechClient;

class SpeechController extends Controller
{
    public function recognize()
    {
        $this->validate($this->request, [
            'audioUri' => 'required|string',
            'phrases' => 'required|string'
        ]);
        $audioUri = $this->request->input('audioUri');
        $phrases = $this->request->input('phrases');
        $hashName = md5($audioUri . time());

        $mp3Path = storage_path('app')  . '/' . $hashName . '.mp3';

        $flacPath = storage_path('app')  . '/' . $hashName . '.flac';

        file_put_contents($mp3Path, file_get_contents($audioUri));

        @exec("ffmpeg -i $mp3Path $flacPath");

        $options = [
            'encoding' => 'FLAC',
            'enableWordTimeOffsets' => true,
            'speechContexts' => [
                'phrases' => [$phrases]
            ]
        ];

        $speech = new SpeechClient([
            'projectId' => 'cd7d4f57959618a6c2d61bc29380802f970b008c',
            'languageCode' => 'en-US'
        ]);

        $results = $speech->recognize(fopen($flacPath, 'r'), $options);

        return $this->sendSuccessJson($results);
    }
}
